<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="hadd(1,'0')">添加权限</el-button>
        </div>
        <el-table row-key="id" default-expand-all border :data="permission">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button v-if="row.type===1" type="text" @click="hadd(2,row.id)">添加</el-button>
              <el-button type="text" @click="hemit(row.id)">编辑</el-button>
              <el-button type="text" @click="hdel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <el-dialog :visible.sync="showDialog" :title="isemit ?'编辑':'添加'" @closed="hClosed">
      <!-- 表单内容 -->
      <el-form ref="addform" :model="formData" label-width="100px" :rules="rules">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="formData.code" />
        </el-form-item>
        <el-form-item label="权限描述">
          <el-input v-model="formData.description" />
        </el-form-item>
        <el-form-item label="权限启用">
          <el-switch
            v-model="formData.enVisible"
            active-text="启用"
            active-value="1"
            inactive-text="不启用"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="text-align: right;">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="hSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { addPermission, delPermission, getPermissionDetail, getPermissionList, updatePermission } from '@/api/premission'
import { tranListToTreeData } from '@/utils'
export default {
  data() {
    const validCode = (rule, value, callback) => {
      let existCodeList = this.originList
      if (this.isEdit) {
        // 编辑时的校验: code能取自己
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      existCodeList.map(it => it.code).includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }
    const validName = (rule, value, callback) => {
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)
      if (this.isEdit) {
        // 编辑时的校验： 名字不能取兄弟（排除自己）的名字
        // 找兄弟，排除自己
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      existNameList.map(it => it.name).includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }
    return {
      permission: [],
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      isemit: false,
      rules: {
        code: [{ message: '不能为空', required: true, trigger: 'blur' }, { validator: validCode, trigger: 'blur' }],
        name: [{ message: '不能为空', required: true, trigger: 'blur' }, { validator: validName, trigger: 'blur' }],
        originList: [] // 在做校验时需要用到的数据
      }
    }
  },
  created() {
    this.loadperminss()
  },
  methods: {
    async loadperminss() {
      const res = await getPermissionList()
      this.originList = res.data.map(({ id, pid, name, code }) => ({ id, pid, name: name.trim(), code }))
      this.permission = tranListToTreeData(res.data)
    },
    hadd(type, pid) {
      this.isemit = false
      this.showDialog = true
      this.formData.type = type
      this.formData.pid = pid
    },
    async hSubmit() {
      const valid = await this.$refs.addform.validate().catch(e => e)
      if (!valid) return
      let res = null
      if (this.isemit) {
        res = await updatePermission(this.formData)
      } else { res = await addPermission(this.formData) }
      try {
        this.$message.success(res.message)
        this.showDialog = false
        this.loadperminss()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    hClosed() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$nextTick(() => {
        this.$refs.addform.clearValidate()
      })
    },
    async  hdel(id) {
      const result = await this.$confirm('真的要删掉么', '提示', { type: 'warning' }).catch(e => e)
      if (!result) return
      try {
        const res = await delPermission(id)
        this.$message.success(res.message)
        this.loadperminss()
      } catch (e) { this.$message.error(e.message) }
    },
    async hemit(id) {
      this.isemit = true
      this.showDialog = true
      const res = await getPermissionDetail(id)
      this.formData = res.data
    }
  }
}
</script>
